#!/usr/bin/env python
# -*- coding: utf-8 -*-


import logging  # 引入logging模块
import csv
import time
import configparser
import os
import sys
from functools import wraps


from threading import Timer


class Timer2(object):
    def __init__(self, second, cb=None, *args):
        self.timeout = None
        self.timer = Timer(second, cb or self.callback, args=args)
        self.timer.start()

    def callback(self, *args):
        # print('call timeout,')
        self.timeout = 1

    def cancel(self, *args):
        # print('call timeout,')
        self.timer.cancel()


def to_hex_list(data):
    # 打印 16进制 list
    return '0x' + ','.join([hex(dd)[2:] for dd in data])


def singleton(cls):
    # 单例装饰器

    instances = {}

    @wraps(cls)
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance


def get_arg(option):
    # print(sys.argv)
    args = sys.argv[1:]
    for index, arg in enumerate(args):
        if arg == option:
            if len(args) > index+1:
                return args[index+1]
    return None


def get_config(name=None):
    if not name:
        name = get_arg('-c')

    if not name:
        return {}

    config = configparser.ConfigParser()
    config.read(name)
    # print(cfg)

    # print( config.sections() )

    return dict((section, dict(config.items(section))
                 )for section in config.sections())


def set_config(name, data):
    # print('set_config,', name, data)
    config = configparser.ConfigParser()

    config.add_section("options")

    for key, value in data.items():
        config.set("options", key,  str(value))

    with open(name, "w") as f:
        config.write(f)


def get_csv_data(name=None):

    if not name:
        name = get_arg('--data')

    if not name:
        return []

    def fn(row, fields):
        # print(',,,', row, meta)
        ret = dict((fld, row[index]) for index, fld in enumerate(fields))
        return ret

    with open(name) as csvfile:
        rows = csv.reader(csvfile)
        recs = [row for row in rows]
        meta = recs[0]
        ret = [fn(rec, meta) for rec in recs[1:]]
        return ret


def set_csv_data(name, data):
    # print('set_csv_data,', name, data)
    with open(name, 'w') as wf:

        if not data:
            return None

        meta = data[0].keys()
        # print('set_csv_data,', meta)
        wf.write(','.join(meta) + '\n')

        for rec in data:
            wf.write(','.join([str(rec[key])for key in meta]) + '\n')


def set_logging(file_name, logging_level=None):
    logger = logging.getLogger()
    if not logging_level:
        logging_level = 'INFO'

    level = getattr(logging, logging_level)
    logger.setLevel(level)

    # logger.setLevel(logging.INFO)
    # logger.setLevel(logging.NOTSET)

    # formatter = logging.Formatter("%(asctime)s - %(pathname)s %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    formatter = logging.Formatter(
        "%(asctime)s %(filename)s:%(lineno)d %(levelname)s: %(message)s")

    log_path = os.getcwd() + '/'
    log_name = log_path + file_name+'.log'
    logfile = log_name
    # print('logfile',logfile)

    file_handle = logging.FileHandler(logfile, mode='a')
    file_handle.setLevel(logging.NOTSET)
    file_handle.setFormatter(formatter)
    logger.addHandler(file_handle)

    console_handle = logging.StreamHandler()
    console_handle.setLevel(logging.NOTSET)
    console_handle.setFormatter(formatter)
    logger.addHandler(console_handle)
